package com.dayuanit.dy15.atm.servlet;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy15.atm.annotation.RequestMapping;
import com.dayuanit.dy15.atm.controller.BaseController;
import com.dayuanit.dy15.atm.controller.CardController;
import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.handler.HanderMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DispatchServlet extends HttpServlet {

    /**
     * servlet有两种初始化的方式，第一种：在第一次访问servlet时，执行初始化的方法
     * 第二种：可以随着服务器启动，而进行初始化。<load-on-startup>1</load-on-startup>
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        System.out.println(">>>>>>>>>>>>>> DispatchServlet init() <<<<<<<<<<<<<<<<<<");
    }

    /**
     * 当servlet重写了两个有参的构造init方法，则以有参的为准
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println(">>>>>>>>>>>>>> DispatchServlet init(ServletConfig)  <<<<<<<<<<<<<<<<");
        System.out.println(config.getInitParameter("username"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>> DispatchServlet begin <<<<<<<<<<<<<<<<<<<<<<");
        //通过key-value键值对数据结构 来消灭if判断
        // key=url   value=Controller
        //通过请求 URL地址，来判别这个请求是做什么业务
        //登录：/user/login.do
        //注册:/user/register.do
        //开户:/card/openaccount.do
        //存款:/card/depsoit.do

//        StringBuffer requestURL = req.getRequestURL();
//        System.out.println("requestURL=" + requestURL.toString());//requestURL=http://127.0.0.1:8088/user/login.do
//
//        String contextPath = req.getContextPath();
//        System.out.println("contextPath=" + contextPath);//contextPath=

        String requestURI = req.getRequestURI();
        System.out.println("requestURI=" + requestURI);//requestURI=/user/login.do

//        String queryString = req.getQueryString();
//        System.out.println("queryString=" + queryString);//queryString=action=abc&username=tom

        String url = req.getRequestURI();
        Object controller = HanderMapping.getController(url);

        Class aClass = controller.getClass();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            //得到当前方法上的注解
            Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
            for (Annotation annotation : declaredAnnotations) {
                if (RequestMapping.class == annotation.annotationType()) {
                    //判断requestmapping注解里的value和当前请求的url是否相等，相等则执行，不相等则继续；
                    RequestMapping requestMapping = (RequestMapping)annotation;
                    String value = requestMapping.value();
                    if (value.equals(url)) {
                        //调用当前method方法
                        Object result = null;
                        try {
                            result = method.invoke(controller, req, resp);
                            //将controller执行的结果响应到客户端
                            //响应的内容包括：页面和json串
                            if (result instanceof String) {
                                response4Page(result.toString(), req, resp);
                            }

                            //异步请求，则响应json串
                            if (result instanceof ResponseDTO) {
                                response4Ajax(result, resp);
                            }

                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                            response4Ajax(ResponseDTO.fail(e.getTargetException().getMessage()), resp);
                        } catch (Exception e) {
                            e.printStackTrace();
                            response4Ajax(ResponseDTO.fail("系统异常，请联系客服"), resp);
                        }
                    }
                }

            }
        }


        System.out.println(">>>>>>>>>>>>>>>>>>>>>> DispatchServlet end <<<<<<<<<<<<<<<<<<<<<<");

    }

    private void response4Ajax(Object object, HttpServletResponse response) {
        String msg = JSON.toJSONString(object);

        try {
            response.setContentType("application/json; charset=utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(msg.getBytes("utf-8"));
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void response4Page(String pageName, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=utf-8");
        try {
            request.getRequestDispatcher("/WEB-INF/page/" + pageName + ".jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
